import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import "bootstrap/dist/css/bootstrap.min.css";
import SearchFile from './components/SearchFile';
import FileList from './components/FileList';
import ButtonItem from './components/ButtonItem';
import TabList from './components/TabList';
import initFiles from './utils/initFiles';
import { faFileImport, faPlus } from '@fortawesome/free-solid-svg-icons';
import SimpleMDE from "react-simplemde-editor";
import "easymde/dist/easymde.min.css";
import { v4 } from 'uuid';
import { mapArr, readFile, writeFile, renameFile, delFile } from './utils/helper';

const path = window.require("path");
const remote = window.require("@electron/remote");
const { ipcRenderer } = window.require("electron");
const Store = window.require("electron-store");

const fileStore = new Store({ "name": "filesInfo" });
// 持久化存储
const saveInfoToStore = (files) => {
  fileStore.set("files", files);
};

// 自定义一个文件存放路径
const savePath = remote.app.getPath("downloads");

// 自定义左侧容器
let LeftDiv = styled.div.attrs({
  className: 'col-3 left-panel'
})`
  background-color: #7b8c7c;
  position: relative;
  .btn_list {
    bottom: 0;
    left: 0;
    right: 0;
    position: absolute;
    p {
      border: 0;
      color: #fff;
      width: 50%;
      margin-bottom: 0;
      border-radius: 0;
    }
    p:nth-of-type(1) {
      background-color: #8ba39e;
    }
    p:nth-of-type(2) {
      background-color: #98b4b3;
    }
  }
`;
// 自定义右侧容器
let RightDiv = styled.div.attrs({
  className: 'col-9 right-panel'
})`
  background-color: #c9d8cd;
  padding: 0!important;
  .init-page {
    font-size: 28px;
    line-height: 300px;
    color: #888;
    text-align: center;
  }
`;

function App() {
  const [files, setFiles] = useState(fileStore.get("files") || {});
  const [searchFiles, setSearchFiles] = useState(initFiles);
  const [activeId, setActiveId] = useState("");
  const [openIds, setOpenIds] = useState([]);
  const [unSaveIds, setUnSaveIds] = useState([]);

  useEffect(() => {
    ipcRenderer.on("execute-create-file", () => {
      console.log("创建了");
    })
  });

  // 新建文件操作
  const createFile = () => {
    const flag = Object.values(files).find(file => file.isNew);
    if (flag) return;
    const newFile = {
      id: v4(),
      title: "",
      isNew: true,
      body: "## 初始化内容",
      createTime: new Date().getTime()
    };
    setFiles({...files, [newFile.id]: newFile});
  };

  // 同步搜索文件
  useEffect(() => {
    setSearchFiles(Object.values(files));
  }, [files]);

  // 计算所有已打开的文件信息
  const openFiles = openIds.map(openId => files[openId]);

  // 计算正在编辑的文件信息
  const activeFile = files[activeId];

  const saveCurrentFile = () => {
    writeFile(activeFile.path, activeFile.body).then(res => {
      setUnSaveIds(unSaveIds.filter(id => id !== activeId));
    });
  };

  // 编辑左侧文件显示编辑页面
  const openItem = (id) => {
    setActiveId(id);
    if (openIds.includes(id)) return;
    const currentFile = files[id];
    // 如果已经加载过则不用加载
    if (currentFile.isLoaded) {
      readFile(currentFile.path).then((data) => {
        const newFile = { ...currentFile, body: data, isLoaded: true }
        setFiles({ ...files, [id]: newFile });
      });
    }
    // 显示标签页
    setOpenIds([...openIds, id]);
  };

  // 通过tab切换文件
  const changeActiveFile = (id) => {
    setActiveId(id);
  };
  // 关闭文件
  const closeFile = (closeId) => {
    const retIds = openIds.filter(id => id !== closeId);
    setOpenIds(retIds);
    // 如果关闭的是活动的,避免取值到变化前的数组
    if (activeId === closeId) setActiveId(retIds[0] || "");
  };

  // 当文件内容更新时
  const changeFile = (id, newValue) => {
    if (!unSaveIds.includes(id)) {
      setUnSaveIds([...unSaveIds, id]); 
    }
    files[id].body = newValue;
    // 更新内容
    setFiles(files);
    // 错误的代码，因为每次files都发生了更新导致文本编辑器重新渲染
    // const newFile = {
    //   ...files[id],
    //   body: newValue
    // };
    // setFiles({ ...files, [id]: newFile });
  };

  // 删除某个文件
  const deleteFile = (id) => {
    delFile(files[id].path)
      .then(() => {
        delete files[id];
        setFiles({...files});
        saveInfoToStore(files);
        closeFile(id);
      });
  };

  // 搜索文件
  const searchFile = (keyWord) => {
    setSearchFiles(Object.values(files).filter(file => file.title.includes(keyWord)));
  };

  // 重命名
  const saveData = (id, newTitle, isNew) => {
    const newPath = path.join(savePath, `${newTitle}.md`);
    const newFile = {
      ...files[id],
      id,
      path: newPath,
      title: newTitle,
      body: files[id]?.body || "",
      isNew: false
    };
    
    ({ // 执行创建
      "true": writeFile(newPath, files[id]?.body),
      // 执行更新
      "false": renameFile(activeFile[id].path, path.join(savePath, `${newTitle}.md`))
    }[isNew])
      .then(() => {
        const newFiles = { ...files, [id]: newFile };
        setFiles(newFiles);
        saveInfoToStore(newFiles);
      });
    
  };

  // 导入文件
  const importFile = () => {
    remote.dialog.showOpenDialog({
      buttonLabel: "请选择",
      title: "选择md文件",
      properties: ["openFile", "multiSelections"],
      filters: [
        { name: "md文档", extensions: ["md"] },
        { name: "其他类型", extensions: ["js", "json", "html"] },
      ]
    })
      .then(res => {
        if (res.filePaths.length === 0) return;
        const vaildPaths = res.filePaths.filter(fpath => Object.values(files).find(file => file.path !== fpath));
        const packageData = vaildPaths.map(fPath => ({
          id: v4(),
          title: path.basename(fPath, ".md"),
          path: fPath,
          body: ""
        }));
        const newFiles = { ...files, ...mapArr(packageData)};
        setFiles(newFiles);
        if (packageData.length) {
          remote.dialog.showMessageBox({
            type: "info",
            title: "导入md文档",
            message: "文件导入成功"
          });
        }
      });
  };

  return (
    <div className="container-fluid px-0">
      <div className="row">
          <LeftDiv>
            <SearchFile title="FISHの文档" onSearch={searchFile}></SearchFile>
            <FileList 
              files={searchFiles} 
              editFile={openItem}
              deleteFile={deleteFile}
              saveFile={saveData}
            />

            <div className="btn_list">
              <ButtonItem title="新建" icon={faPlus} btnClick={createFile} />
              <ButtonItem title="导入" icon={faFileImport} btnClick={importFile} />
            </div>
          </LeftDiv>
          <RightDiv>
            {
              activeId ? 
              <>
                <button onClick={saveCurrentFile}>保存</button>
                <TabList
                  files={openFiles}
                  activeItem={activeId}
                  unSaveItems={unSaveIds}
                  clickItem={changeActiveFile}
                  closeItem={closeFile}
                ></TabList>
                <SimpleMDE
                  key={activeId}
                  onChange={(value) => { changeFile(activeFile.id, value) }}
                  value={activeFile?.body} 
                  options={{
                    autofocus: true,
                    spellChecker: false,
                    minHeight: "350px"
                  }}
                />
              </>
              :
              <>
                <div className='init-page'>新建或者导入文件</div>
              </>
            }
          </RightDiv>
      </div>
    </div>
  );
}

export default App;
